package com.itheima.demo04;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipStreamDemo02 {
    public static void main(String[] args) {
        // 创建一个压缩流
        File src = new File("a.txt");

        // 创建存放压缩文件的目录
        File dest = new File("a.zip");

        toZip(src, dest);

    }

    public static void toZip(File src, File dest) {
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(dest));
            // 压缩文件
            zos.putNextEntry(new ZipEntry(src.getName()));
            // 读取文件内容
            byte[] buffer = new byte[1024];
            int len;
            InputStream is = new FileInputStream(src);
            while ((len = is.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zos!= null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
